package com.jl15988.chainlog.controller;

import com.jl15988.chainlog.annotation.ChainController;
import com.jl15988.chainlog.annotation.ChainCustom;
import com.jl15988.chainlog.constant.ChainLogConstant;
import com.jl15988.chainlog.model.ChainApiLog;
import com.jl15988.chainlog.model.ChainTraceTree;
import com.jl15988.chainlog.service.ChainTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 链式跟踪可视化控制器
 */
@Controller
@RequestMapping("/chain-trace")
@ConditionalOnProperty(prefix = "chain-log.visualization", name = "enabled", havingValue = "true", matchIfMissing = true)
@ChainController(module = "可视化监控", desc = "链式跟踪可视化控制器", customs = {
        @ChainCustom(key = ChainLogConstant.ChainTraceControllerKey)
})
public class ChainTraceController {

    @Autowired
    private ChainTraceService chainTraceService;

    /**
     * 主页面
     */
    @GetMapping
    public String index() {
        return "chain-log/index";
    }

    /**
     * 获取最近的API调用列表
     */
    @GetMapping("/api/recent")
    @ResponseBody
    public ResponseEntity<List<ChainApiLog>> getRecentApiLogs(@RequestParam(defaultValue = "50") int limit) {
        List<ChainApiLog> logs = chainTraceService.getRecentApiLogs(limit);
        return ResponseEntity.ok(logs);
    }

    /**
     * 获取最近的所有调用链
     */
    @GetMapping("/api/recent-chains")
    @ResponseBody
    public ResponseEntity<List<Object>> getRecentChains(@RequestParam(defaultValue = "50") int limit) {
        List<Object> chains = chainTraceService.getRecentChains(limit);
        return ResponseEntity.ok(chains);
    }

    /**
     * 搜索API日志
     */
    @GetMapping("/api/search")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> searchApiLogs(
            @RequestParam(required = false) String url,
            @RequestParam(required = false) String method,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) Long startTime,
            @RequestParam(required = false) Long endTime,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        List<ChainApiLog> logs = chainTraceService.searchApiLogs(url, method, module, startTime, endTime, page, size);

        Map<String, Object> result = new HashMap<>();
        result.put("data", logs);
        result.put("page", page);
        result.put("size", size);
        result.put("total", logs.size());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取调用链详情
     */
    @GetMapping("/api/{rootId}/trace")
    @ResponseBody
    public ResponseEntity<ChainTraceTree> getTraceTree(@PathVariable String rootId) {
        ChainTraceTree tree = chainTraceService.getTraceTree(rootId);
        if (tree == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(tree);
    }

    /**
     * 调用链详情页面
     */
    @GetMapping("/detail/{rootId}")
    public String traceDetail(@PathVariable String rootId, Model model) {
        model.addAttribute("rootId", rootId);
        return "chain-log/detail";
    }

    /**
     * 清理过期数据
     */
    @PostMapping("/api/clean")
    @ResponseBody
    public ResponseEntity<Map<String, String>> cleanExpiredData(@RequestParam(defaultValue = "86400000") long expireTime) {
        chainTraceService.cleanExpiredData(expireTime);

        Map<String, String> result = new HashMap<>();
        result.put("message", "Expired data cleaned successfully");

        return ResponseEntity.ok(result);
    }
}